﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Eqwww.Data;
using Eqwww.Domain.Models.SystemManage;
using Eqwww.App.SystemManage;
using Eqwww.Code;
using Eqwww.App.Identity;
using Eqwww.App.Authorize;
using Eqwww.Domain.Models.Identity;
using AutoMapper;
using Eqwww.Web.Areas.SystemManage.Models.Role;

namespace Eqwww.Web.Areas.SystemManage.Controllers
{
    [Area("SystemManage")]
    public class RoleController : ControllerBase
    {
        private RoleApp _roleApp;
        private AuthorizeApp _authorizeApp;
        private StrategoryApp _strategoryApp;
        private IMapper _mapper;

        public RoleController(RoleApp roleApp, 
            AuthorizeApp authorizeApp, 
            StrategoryApp strategoryApp,
            IMapper mapper)
        {
            _roleApp = roleApp;
            _authorizeApp = authorizeApp;
            _strategoryApp = strategoryApp;
            _mapper = mapper;
        }

        [AuthFilter]
        public IActionResult Index()
        {
            var currentModuleCode = "SystemManage_Role";
            ViewData["SelectedButtons"] = _authorizeApp.GetAuthorizedModuleButtons(User, currentModuleCode, ModuleButtonPosition.Selected);
            ViewData["InitialButtons"] = _authorizeApp.GetAuthorizedModuleButtons(User, currentModuleCode, ModuleButtonPosition.Initial);

            return View();
        }

        [AuthFilter]
        public async Task<IActionResult> Details(string id)
        {
            if (id == null)
                return NotFoundObject();
            
            var model = await _roleApp.FindByIdAsync(id);
            if (model == null)
                return NotFoundObject();
            ViewData["Strategorys"] = _strategoryApp.GetStrategorysByRoleId(id);
            return View(model);
        }

        [AuthFilter]
        public IActionResult Create()
        {
            return View();
        }

        
        [HttpPost]
        [ExceptionFilter]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("Name, ShowName, CanYuFaHuo,SortCode, Description")] CreateViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                var model = _mapper.Map<RoleModel>(viewModel);
                return Json(await _roleApp.AppCreateAsync(model));
            }
            return Json(Common.ModelStateErrorResult(ModelState));
        }

        [AuthFilter]
        public async Task<IActionResult> Edit(string id)
        {
            if (id == null)
                return NotFoundObject();
            var model = await _roleApp.FindByIdAsync(id);
            
            if (model == null)
                return NotFoundObject();
            if (model.IsSystem == true)
                return ErrorView("系统角色不允许修改！");
            var viewModel = _mapper.Map<EditViewModel>(model);
            return View(viewModel);
        }

        
        [HttpPost]
        [ExceptionFilter]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(string id, [Bind("ShowName,SortCode,Id,Name, Description")] EditViewModel viewModel)
        {
            if (id != viewModel.Id)
            {
                return Error("Get Id和Post Id不一致");
            }

            if (ModelState.IsValid)
            {

                var model = _roleApp.FindByIdAsync(id).Result;
                _mapper.Map(viewModel, model);
                return Json(await _roleApp.AppUpdateAsync(model));

            }

            return Json(Common.ModelStateErrorResult(ModelState));
        }

        

        // POST: SystemManage/Role/Delete/5
        [HttpPost, ActionName("Delete")]
        [ExceptionFilter]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(string id)
        {
            return Json(await _roleApp.AppRemoveAsync(id));
        }

        [AuthFilter]
        public IActionResult StrategoryManage(string id)
        {
            var model = _roleApp.FindByIdAsync(id).Result;
            if (model == null)
                return ErrorView("未查询到指定实体");
            if (model.IsSystem == true)
                return ErrorView("系统角色不允许修改");
            ViewData["Items"] = _strategoryApp.GetAllStrategorysByRoleId(id);
            return View();
        }

        [HttpPost,ActionName("StrategoryManage")]
        [ExceptionFilter]
        [ValidateAntiForgeryToken]
        public IActionResult StrategoryManageConfirmed(string roleId, string strategorys)
        {
            var ss = string.IsNullOrEmpty(strategorys) ? new string[] { } : strategorys.Split(',');
            return Json(_strategoryApp.UpdateRelatedRolesByRoleId(roleId, ss));
        }

        public IActionResult Claims(string roleId)
        {

            var role=_roleApp.FindByIdAsync(roleId).Result;
            var claims=_roleApp.GetClaimsAsync(role).Result;
            ViewData["Claims"]=claims;
            return View();
        }

        [HttpPost]
        [ExceptionFilter]
        [ValidateAntiForgeryToken]
        public IActionResult ClaimsForm(string roldId)
        {
            
            return Success("操作成功!");
        }


        public IActionResult GridJson(Pagination pagination)
        {
            var roles = _roleApp.GetPagedIQueryable(pagination);
            var rows = _mapper.Map<List<IndexViewModel>>(roles);
            var data = new
            {
                rows = rows,
                total = pagination.total,
                page = pagination.page,
                records = pagination.records
            };
            return Content(data.ToJson());
        }

        [HttpPost]
        [ExceptionFilter]
        [ValidateAntiForgeryToken]
        public IActionResult UpdateIsSystem(string id)
        {
            return Json(_roleApp.UpdateIsSystem(id, true));
        }

        [HttpPost]
        [ExceptionFilter]
        [ValidateAntiForgeryToken]
        public IActionResult UpdateIsNotSystem(string id)
        {
            return Json(_roleApp.UpdateIsSystem(id, false));
        }
    }
}
